import { getChannelinfo, wxMiniCorpLogin,getUserInfo, logout } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
// import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  tenantId: '',
  userInfo:{}
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_CORPID: (state, corpId) => {
    state.corpId = corpId
  },
  SET_TENANTID: (state, tenantId) => {
    state.tenantId = tenantId
  }
}
const actions = {
  // user login
  login({ commit }, data) {
    return new Promise((resolve, reject) => {
      wxMiniCorpLogin(data)
        .then((response) => {
          commit('SET_TOKEN', response.access_token)
          setToken(response.access_token)
          localStorage.setItem('userInfo',  JSON.stringify(response))
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // get user info
  getUserInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo()
        .then((response) => {
          commit('SET_USERINFO', response)
          localStorage.setItem('userInfo',  JSON.stringify(response))
          resolve(response)
        })
        .catch((error) => {
          resolve(error)
        })
    })
  },
  getChannelinfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getChannelinfo()
        .then((response) => {
            console.log(response)
            if(response) {
                const { tenantId, corpId, tenantName, tenantLogoUrl } = response
                // 暂时无用
                commit('SET_CORPID', corpId)
                commit('SET_TENANTID', tenantId)
                localStorage.setItem('tenantId', tenantId)
                localStorage.setItem('tenantInfo', JSON.stringify({ tenantName, tenantLogoUrl }))
            }

          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      // logout(state.token)
      logout()
        .then(() => {
          removeToken()
          // resetRouter()
          // location.reload()
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
